$(function () {
    var form = window.form_query;
    var now = moment().format("YYYY-MM-DD");
    var timeLimitStart = form.timeLimitStart.value;
    var timeLimitEnd = form.timeLimitEnd.value;
    var startDate = moment(now).subtract(30, 'days').startOf('day');
    var lastmonth = moment().subtract(1, 'months');


    var endDate = moment(now).endOf('day');
    if (timeLimitStart && timeLimitEnd) {
        startDate = moment(parseInt(timeLimitStart));
        endDate = moment(parseInt(timeLimitEnd));
    }
    if(!timeLimitStart){
        form.timeLimitStart.value = startDate.startOf('day').format("x");
    }
    if(!timeLimitEnd){
        form.timeLimitEnd.value = endDate.startOf('day').format("x");
    }

    $('#stats_data_start').daterangepicker({
        "singleDatePicker": true,
        "timePicker": false,
        "startDate": startDate,
        //"timePicker24Hour": true,
        //"timePickerSeconds": true,
        //"minDate":lastmonth,
        "maxDate": now,
        "autoApply": true,
        "parentEl": "200",
        locale: {
            format: 'YYYY-MM-DD',
            applyLabel: '确认',
            cancelLabel: '取消',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek:["日","一","二","三","四","五","六"],
            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
        }
    }, function(start, end, label) {
        form.timeLimitStart.value = start.startOf('day').format("x");
        // $('#stats_data_start').val(start.startOf('day').format("x"));
    });
    //$('#stats_data_start').val("");//清空控件默认时间

    $('#stats_data_end').daterangepicker({
        "singleDatePicker": true,
        "timePicker": false,
        "startDate": endDate,
        //"timePicker24Hour": true,
        //"timePickerSeconds": true,
        "autoApply": true,
        //"minDate":lastmonth,
        "maxDate": now,
        "parentEl": "200",
        locale: {
            format: 'YYYY-MM-DD',
            applyLabel: '确认',
            cancelLabel: '取消',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek:["日","一","二","三","四","五","六"],
            monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
        }
    }, function(start, end, label) {
        form.timeLimitEnd.value = start.endOf('day').format("x");
        // $('#stats_data_end').val(start.startOf('day').format("x"));
    });
    
     //获取产品列表
    $.get("/stastics/getProList", function (re) {
        var proList = re.data;
        var proOptions = "<option value=''> 全部产品 </option>";
        for (var i in proList) {
            var pro = proList[i];
            proOptions += "<option value='" + pro.id + "'>" + pro.name + "</option>";
        }
        $("#product_list").html(proOptions);
    });
    init();
    function init(){
    	$.get("/stastics/getxAxisyAxisData?productId="+form.product_list.value+"&timeStart="+form.timeLimitStart.value+"&timeEnd="+form.timeLimitEnd.value, function (re) {
    		var Data =  re.data;
    		showChart(Data.xAxisData,Data.scanNum,Data.userNum);
        });
    }
    
	function showChart(xAxisData,scanNum,userNum){
		//初始化echarts
    	var myChart = echarts.init(document.getElementById("main"));
    	option = {
    		    tooltip: {
    		        trigger: 'axis',
    		        axisPointer: {type: 'cross'}
    		    },
    		    color:["#0099FF","#D87A80","#F39C12"],
    		    toolbox: {
    		        feature: {
    		            //dataView: {show: true, readOnly: false},
    		            restore: {show: true},
    		            saveAsImage: {show: true}
    		        }
    		    },
    		    legend: {
    		        data:['扫码量/次','用户量/人']
    		    },
    		    grid: {
    		        left: '3%',
    		        right: '4%',
    		        bottom: '3%',
    		        containLabel: true
    		    },
    		    xAxis: [
    		        {
    		            type: 'category',
    		            data: xAxisData,
    		            scale: true,
    		            boundaryGap : false,
    		            axisLine: {onZero: false},
    		            splitLine: {show: false},
    		            splitNumber: 20
    		        }
    		    ],
    		    yAxis: [
    		        {
    		            type: 'value',
    		            name: '扫码量/次',
    		            interval: 200,
    		            splitLine: {
    		                show: false
    		            },
    		            axisLabel: {
    		                formatter: '{value}'
    		            }
    		        },
    		        {
    		            type: 'value',
    		            name: '用户量/人',
    		            interval: 200,
    		            splitLine: {
    		                show: false
    		            },
    		            axisLabel: {
    		                formatter: '{value}'
    		            }
    		        }
    		    ],
    		    series: [
    		       
    		        {
    		            name:'扫码量/次',
    		            type:'line',
    		            data:scanNum
    		        },
    		        {
    		            name:'用户量/人',
    		            type:'line',
    		            yAxisIndex: 1,
    		            data:userNum
    		        }
    		    ]
    		};
    	
    	//使用指定配置项和数据显示图表
    	myChart.setOption(option);
	}
	
	
	$("[name='btn_search']").click(function () {
    	var product_list = (form.product_list.value == "全部产品" ? "" : form.product_list.value);
    	$.get("/stastics/getxAxisyAxisData?productId="+product_list+"&timeStart="+form.timeLimitStart.value+"&timeEnd="+form.timeLimitEnd.value, function (re) {
    		var Data =  re.data;
    		showChart(Data.xAxisData,Data.scanNum,Data.userNum);
        });
    	getlistDataByHour(1);
    });

	//数据导出
	$("[name='btn_export']").click(function () {
	    //有数据时才能导出
	    if($("#resultTotal_hidden").val() != 0){
	    	bootbox.bconfirm("确定是否导出？", function (re) {
	            if (re) {
	            	 var product_list = (form.product_list.value == "全部产品" ? "" : form.product_list.value);
	            	 var url="/stastics/DataByHourExport?productId="+product_list+"&timeStart="+form.timeLimitStart.value+"&timeEnd="+form.timeLimitEnd.value;
	                 window.open(url);
	            }
	        });
	    }else{
	    	bootbox.balert("没有数据，无法导出!");
	    }
	});
	getlistDataByHour(1);
	function getlistDataByHour(page){
		var product_list = (form.product_list.value == "全部产品" ? "" : form.product_list.value);
        page = page || 1;
        var  url ="/stastics/getlistDataByHour?productId="+product_list+"&timeStart="+form.timeLimitStart.value+"&timeEnd="+form.timeLimitEnd.value+"&page=" +page;
        $.post(url, function (re) {
            var result = re.data, resultList=result.result;
            var str = "";
            for(var i=0; i<resultList.length; i++){
                var para = resultList[i];
                str += '<tr>' +
                    '<td>'+para.xtime +'</td>'+
                    '<td>'+ para.SCANCOUNT + '</td>'+
                    '<td>'+ para.scanpsn + '</td>' +
                    '<td>'+ para.WINCOUNT + '</td>' +
                    '<td>'+ para.REDPACKCOUNT + '</td>' +
                    '<td>'+ para.ENTITYCOUNT + '</td>' +
                '</tr>';
            }
            $('#tbody_data').html(str);
            resetPage(result.pageTotal, page);

        });
	}
	//分页

    function resetPage(totalPage, currPage){
        var innerHTML = [];
        currPage = currPage || 1;
        innerHTML.push('<ul class="pagination pagination-sm no-margin">');
        if(currPage > 1){
            innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
        }
        if(currPage - 4 > 1){
            innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
        }
        for(var i = currPage - 3; i < currPage; i++){
            if(i > 1){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        innerHTML.push('<li class="active"><span>', currPage,'</span></li>')
        for(var i = currPage+1; i < currPage+3; i++){
            if(i < totalPage){
                innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
            }
        }
        if(currPage < totalPage - 3){
            innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
        }
        if(currPage < totalPage){
            innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
                '<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
        }
        innerHTML.push("</ul>")
        $("#page_model").data("total", totalPage).html(innerHTML.join(""));
    }

    $("#page_model").on("click", "li", function () {
        if($(this).hasClass("active")){
            return false;
        }
        var currPage = parseInt($("#page_model .active").text()),
            totalPage = $("#page_model").data("total");
        if($(this).hasClass("prev")){
            currPage--;
        } else if($(this).hasClass("next")){
            currPage++;
        } else if($(this).hasClass("bigPrev")){
            currPage -= 5;

            if(currPage < 1){
                currPage = 1;
            }
        } else if($(this).hasClass("bigNext")){
            currPage += 5;

            if(totalPage - currPage < 0){
                currPage = totalPage;
            }
        } else {
            currPage = parseInt($(this).text());
        }

        getlistDataByHour(currPage);
    })
});